package com.lhm.service;

import com.lhm.dao.BookDao;
import com.lhm.dao.MatterDao;
import com.lhm.entity.Book;
import com.lhm.entity.My;
import com.lhm.entity.MyMatter;
import com.lhm.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class BookServiceImpl implements BookService {

    @Autowired
    BookDao bookDao;
    @Autowired
    MatterDao matterDao;

    @Override
    public List<Book> findByPage(int start, int num) {
        return bookDao.findByPage(start, num);
    }

    @Override
    public List<Book> findByTypeid(String typeid) {
        return bookDao.findByTypeid(typeid);
    }

    @Override
    @Transactional
    public String addBook(My my) {
        MyMatter m = new MyMatter();
        m.setDetails(my.getDetails());
        MyMatter matter1 = matterDao.addMatter(m);
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        System.err.println(user);
        System.out.println(user+"***********************");
        if (user != null){
            Book boke = new Book();
            boke.setUid(user.getId());//用户id
            boke.setTypeid(my.getTypeid());//类型
            boke.setTitle(my.getTitle());//标题
            boke.setMatter(my.getMatter().substring(0,200));//摘要
            boke.setDetaid(matter1.getId());//内容id
            boke.setRum(0);//阅读人数
            boke.setTime(new Date());
            bookDao.addBoke(boke);
        }
        return "添加";
    }

    @Override
    public String delById(String id) {
                bookDao.delById(id);
                return "删除";
    }

    @Override
    public List<Book> findAll() {
        return bookDao.findAll();
    }

    @Override
    public List<Book> findBy(String title) {
        return bookDao.findBy(title);
    }

    @Override
    public List<Book> findByUid() {
        Object object = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        User user = (User) object;
        return bookDao.findByUid(user.getId());
    }

    @Override
    public MyMatter findById(String id) {
        MyMatter myMatter = matterDao.findById(id);
        return myMatter;
    }
}
